import java.util.Date;
import java.io.File;
import java.io.IOException;
import java.util.logging.*;
import java.text.SimpleDateFormat;
import java.text.MessageFormat;

class SimplestFormatter extends Formatter {
    private static final SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");

    @Override
    public String format(LogRecord record) {
        String time = dateFormat.format(new Date(record.getMillis()));
        return time + " " + record.getMessage() + "\n";
    }
};


class Log {

    public static Logger logger;

    public static void init() {
        logger = Logger.getLogger("carrot-logger");

        try {
            if (Property.logFile != null) {
                // Set up a FileHandler to log to a file
                FileHandler fileHandler = new FileHandler(Property.logFile, true);
                fileHandler.setLevel(Level.ALL);
                fileHandler.setFormatter(new SimplestFormatter());
                logger.addHandler(fileHandler);
            }

            Handler consoleHandler = new ConsoleHandler();
            consoleHandler.setFormatter(new SimplestFormatter());
            logger.addHandler(consoleHandler);
            logger.setUseParentHandlers(false);

            // Set the logger level to ALL
            logger.setLevel(Level.ALL);
        } catch (IOException e) {
            logger.log(Level.SEVERE, "Error occurred in setting up the file handler", e);
        }
        return;
    }

    public static void debug(String msg) {
        logger.fine("DEBUG : " + msg);
    }

    public static void print(String msg) {
        logger.info(msg);
    }

    public static void info(String msg) {
        logger.info("INFO : " + msg);
    }

    public static void warning(String msg) {
        logger.warning("WARNING : " + msg);
    }

    public static void err(String msg) {
        logger.severe("ERROR : " + msg);
    }

    public static void except(Exception e) {
        StringBuilder sb = new StringBuilder();
        for (StackTraceElement ele : e.getStackTrace()) {
            sb.append(MessageFormat.format("\tat {0}.{1}({2}:{3})\n", ele.getClassName(), ele.getMethodName(), ele.getFileName(), ele.getLineNumber()));;
        }

        logger.severe("Exception: " + e.getMessage() + "\n" + sb.toString());
    }
};

